package com.traffic.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.ArrayMap;
import com.traffic.annotation.ApiJsonObject;
import com.traffic.annotation.ApiJsonProperty;
import com.traffic.constant.Status;
import com.traffic.entity.*;

import com.traffic.exception.BaseException;
import com.traffic.model.ApiResponse;

import com.traffic.model.ComplaintResult;
import com.traffic.model.LabelResult;
import com.traffic.service.*;
import com.traffic.util.BaidumapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "标签相关接口")
@RestController
@RequestMapping(value = "/label")
@Slf4j
public class LabelController {


    @Autowired
    LabelService labelService;

    @Autowired
    BaidumapUtil baidumapUtil;

    @Autowired
    BaidumapService baidumapService;

    @Autowired
    UserService userService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    PushService pushService;

    @Autowired
    ComplaintService complaintService;

    @Autowired
    ResourceService resourceService;


    @ApiOperation(value = "【标签列表】", notes = "标签列表")
    @ApiImplicitParam(paramType = "path", dataType = "Integer", name = "page", value = "当前页数", required = true)
    @GetMapping("/labellist/{page}")
    public ApiResponse LabelList(@PathVariable Integer page) {

        Integer count = labelService.count();

        IPage<Label> labelIPage = new Page<Label>(page, 10,count);
        IPage<Label> labelbacks = labelService.page(labelIPage);

        return ApiResponse.ofStatus(Status.OK, labelbacks);

    }

    @ApiOperation(value = "【标签列表】", notes = "全部标签（无需参数）")
    @GetMapping("/alllabel")
    public ApiResponse AllLabel() throws ParseException{


        QueryWrapper<Label> wrapper= new QueryWrapper<>();
        List<Label> targetlabel = labelService.list(wrapper.last("where endtime > now()"));

//        for (Label l:targetlabel) {
//            UpdateWrapper<Label> updatewrapper = new UpdateWrapper<>();
//            labelService.update(updatewrapper.set("click",l.getClick()+1).eq("id",l.getId()));
//        }

        return ApiResponse.ofStatus(Status.OK, targetlabel);

    }

    @ApiOperation(value = "【标签列表】", notes = "全部标签（无需参数）")
    @GetMapping("/alllabel/{longitude}/{latitude}/{userid}")
    public ApiResponse userLabel(@PathVariable Float longitude,@PathVariable Float latitude, @PathVariable Integer userid) throws ParseException{

        QueryWrapper<Label> wrapper= new QueryWrapper<>();
        List<Label> targetlabel = labelService.list(wrapper.last("where endtime > now()"));


        List<Label> rLabel = new ArrayList<>();
        List<LabelResult> labelResults = new ArrayList<>(0);

        for (Label l:targetlabel) {
            String point = l.getPoint();
            Float lo = Float.parseFloat(point.split(",")[0]);
            Float la = Float.parseFloat(point.split(",")[1]);

            if (Math.abs(longitude-lo)<=0.04 && Math.abs(latitude-la)<=0.04){
                rLabel.add(l);
            }

        }
        boolean empty = false;
        boolean flag=false;
        for (Label l:rLabel) {

            if(ObjectUtil.isEmpty(l.getClickuser()))empty=true;
            if(empty == false){
                flag =l.getClickuser().contains(userid.toString());
            }
            if(empty || flag==false){

                l.setClick(l.getClick()+1);
                l.setClickuser(l.getClickuser()+"|"+userid.toString());
                labelService.updateById(l);
            }
            LabelResult temp = new LabelResult();
            temp.setId(l.getId());
            temp.setAddress(l.getAddress());
            temp.setClick(l.getClick());
            temp.setFormataddress(l.getFormataddress());
            temp.setUserId(l.getUserId());
            temp.setCreatetime(l.getCreatetime());
            temp.setEndtime(l.getEndtime());
            temp.setType(l.getType());
            temp.setPass(l.getPass());
            temp.setPoint(l.getPoint());
            temp.setTime(l.getTime());
            temp.setUp(l.getUp());
            temp.setDown(l.getDown());
            if(l.getClickuser().contains(userid.toString())){
                temp.setIsclick(true);
            }else {
                temp.setIsclick(false);
            }
            if(l.getUpuser().contains(userid.toString())){
                temp.setIsup(true);
            }else {
                temp.setIsup(false);
            }
            labelResults.add(temp);

        }

        return ApiResponse.ofStatus(Status.OK, labelResults);

    }



    @ApiOperation(value = "【标签】", notes = "删除标签")
    @ApiImplicitParam(paramType = "path", dataType = "Integer", name = "deleteId", value = "删除标签的id", required = true)
    @DeleteMapping(value = "/delete/{deleteId}")
    public ApiResponse deleteLabel(@PathVariable Long deleteId) {

        labelService.removeById(deleteId);

        return ApiResponse.ofStatus(Status.OK);
    }

    @ApiOperation(value = "【标签】", notes = "编辑标签")
    @PostMapping("/update")
    public ApiResponse updateLabel(@RequestBody Map<String,String> param) {

        Label label = new Label();

        label.setId(new Integer(param.get("id")));
        label.setType(param.get("type"));
        label.setPass(param.get("pass"));
        label.setTime(new Integer(param.get("time")));

        labelService.updateById(label);

        return ApiResponse.ofStatus(Status.OK);

    }

    @ApiOperation(value = "【标签】", notes = "关键词模糊查询标题")
    @PostMapping("/search")
    @ApiJsonObject(name = "param",value = {
            @ApiJsonProperty(type =String.class,key = "address",example = "xx省xx市xx区xxxx" , description = "地址"),
            @ApiJsonProperty(type =String.class,key = "type",example = "封路" , description = "类型"),
            @ApiJsonProperty(type =String.class,key = "pass",example = "无法通行" , description = "通行情况"),
            @ApiJsonProperty(type =String.class,key = "starttime",example = "2020-10-28 12:00:00" , description = "筛选开始时间"),
            @ApiJsonProperty(type =String.class,key = "endtime",example = "2020-10-28 12:00:00" , description = "筛选结束时间")

    })
    public ApiResponse searchLabel(@RequestBody Map<String, String> param) throws ParseException {

        String address= ""+param.get("address");
        String type = ""+param.get("type");
        String pass = ""+param.get("pass");
        String starttime = ""+param.get("starttime");
        String endtime = ""+param.get("endtime");


        List<Label> labels =  labelService.queryTargetLabel(starttime,endtime,type,pass,address);
        if (labels.isEmpty()) {
            return ApiResponse.ofStatus(Status.OK);
        }else {
            return ApiResponse.ofStatus(Status.OK, labels);
        }
    }

    @ApiOperation(value = "【标签】", notes = "新增标签")
    @PostMapping("/insert")
    @ApiJsonObject(name = "label",value = {
            @ApiJsonProperty(type =String.class,key = "type",example = "拥堵" , description = "类型名称"),
            @ApiJsonProperty(type =String.class,key = "createtime",example = "2020-10-10 08:30:52" , description = "开始时间"),
            @ApiJsonProperty(type =String.class,key = "time",example = "2020-10-21 08:30:52" , description = "结束时间"),
            @ApiJsonProperty(type =String.class,key = "userid",example = "302" , description = "用户id"),

    })
    public ApiResponse insertLabel(@RequestBody Map<String, Object> label) {

        String param[] = new String[]{"type","pass","point","time","userid"};

        List<String> paramList = CollUtil.newArrayList(param);


        Label lab = new Label();
        BeanUtil.copyProperties(label, lab, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        lab.setCreatetime(now);

        if(lab.getTime()==-1){
            Calendar cal=Calendar.getInstance();
            cal.setTime(now);
            cal.add(Calendar.DAY_OF_MONTH,1);
            cal.set(Calendar.HOUR_OF_DAY, 5);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            lab.setEndtime(cal.getTime());
            Long ntime = (cal.getTime().getTime()-now.getTime())/60000;
            lab.setTime(Integer.parseInt(ntime.toString()));

        }else{
            lab.setEndtime(new Date(now .getTime() + 60000*lab.getTime()));
        }




        String point = lab.getPoint();
        String ak = baidumapUtil.getAk();

        Double longitude = new Double(point.split(",")[0]);
        Double latitude = new Double(point.split(",")[1]);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("location", latitude.toString()+","+longitude.toString());
        params.put("ak", ak);

        String address = baidumapService.getAddress(params);
        JSONObject json = JSON.parseObject(address).getJSONObject("result");

        //JSONObject formataddress = json.getJSONObject("formatted_address");
        String format = json.getString("formatted_address");
        String naddress = json.getString("sematic_description");
        lab.setAddress(naddress.split(",")[0]);
        lab.setFormataddress(format);

        System.out.println(naddress);
        System.out.println(format);

        lab.setClickuser("|");
        lab.setUpuser("|");
        lab.setUserId(Long.parseLong(label.get("userid").toString()));
        labelService.save(lab);

        return ApiResponse.ofStatus(Status.OK,lab.getId());
    }

    @ApiOperation(value = "【标签列表】", notes = "获取单个标签")
    @ApiImplicitParam(paramType = "path", dataType = "Integer", name = "id", value = "标签id", required = true)
    @GetMapping("/getlabel/{id}")
    public ApiResponse getLabel(@PathVariable Integer id) {

        Label lll = labelService.getById(id);

        return ApiResponse.ofStatus(Status.OK, lll);

    }


    @ApiOperation(value = "【标签列表】", notes = "点赞")
    @ApiImplicitParam(paramType = "path", dataType = "Integer", name = "id", value = "标签id", required = true)
    @GetMapping("/getups/{id}/{userid}")
    public ApiResponse getUps(@PathVariable Integer id, @PathVariable Integer userid) {

        Label l = labelService.getById(id);

        String oriups = l.getUpuser();
        if(oriups.contains(userid.toString()))return ApiResponse.ofStatus(Status.OK,"点赞成功");

        l.setUpuser(oriups+"|"+userid.toString());
        l.setUp(l.getUp()+1);
        labelService.updateById(l);

        User u = userService.getById(l.getUserId());


        String content = "有人给你在"+l.getFormataddress()+"的路况标签点赞啦";
        String title = "收到点赞";
        String user=u.getRegistrationid();

        Message me = Message.builder().acceptuser(user).title(title).content(content).type(1).createtime(new Date()).build();

        pushService.save(me);

        return ApiResponse.ofStatus(Status.OK,"点赞成功");

    }


    @ApiOperation(value = "【标签列表】", notes = "点赞")

    @PostMapping("/complaint/upload")
    @ApiJsonObject(name = "label",value = {
            @ApiJsonProperty(type =String.class,key = "labelid",example = "3" , description = "路况标签id"),
            @ApiJsonProperty(type =String.class,key = "content",example = "这队伍排的也太长了吧" , description = "吐槽内容"),
            @ApiJsonProperty(type =String.class,key = "userid",example = "6" , description = "用户id"),

    })
    public ApiResponse uploadComplaint(@RequestBody Map<String, Object> param) {

        Long lableid = Long.parseLong(param.get("labelid").toString());
        Long userid = Long.parseLong(param.get("userid").toString());
        String content = param.get("content").toString();

        Complaint com = Complaint.builder().labelId(lableid).userId(userid).content(content).createtime(new Date()).build();

        complaintService.save(com);

        Label l = labelService.getById(lableid);

        UpdateWrapper<Label> wrapper = new UpdateWrapper<>();
        labelService.update(wrapper.set("down",l.getDown()+1).eq("id",l.getId()));

        User u = userService.getById(l.getUserId());

        String pcontent = "有人吐槽你在"+l.getFormataddress()+"的路况标签:"+content;
        String title = "收到吐槽";
        String user=u.getRegistrationid();

        Message me = Message.builder().acceptuser(user).title(title).content(pcontent).type(1).createtime(new Date()).build();

        pushService.save(me);

        return ApiResponse.ofStatus(Status.OK,"吐槽成功");

    }

    @ApiOperation(value = "【标签列表】", notes = "获取单个标签")
    @ApiImplicitParam(paramType = "path", dataType = "Integer", name = "id", value = "标签id", required = true)
    @GetMapping("/complaint/list/{id}")
    public ApiResponse getDowns(@PathVariable Integer id) {

        QueryWrapper<Complaint> wrapper = new QueryWrapper<>();
        List<Complaint> complaints = complaintService.list(wrapper.eq("label_id",id));

        List<ComplaintResult> complaintResults = new ArrayList<>();

        for (Complaint com : complaints) {
            ComplaintResult temp = new ComplaintResult();
            temp.setContent(com.getContent());
            temp.setCreatetime(com.getCreatetime());

            UserInfo u = userInfoService.getUserInfoByUserId(com.getUserId());
            temp.setNickname(u.getNickName());
            Long img = u.getHeadImg();

            temp.setHeadimg(resourceService.getImgUrl(img));

            complaintResults.add(temp);

        }

        return ApiResponse.ofStatus(Status.OK,complaintResults);

    }



}
